//
//  UserSettings.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/9.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "UserSettings.h"
#import "StringUtil.h"
#import "FileUtil.h"
#import "UserCacheInfoModel.h"

@interface UserSettings ()

// 沙盒对象
@property (nonatomic, strong) NSUserDefaults *userDefaults;
@end


@implementation UserSettings

- (instancetype)init
{
    if (self = [super init]) {
        _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"UserLoginInfo"];
    }
    return self;
}

+ (instancetype)sharedInstance
{
    static UserSettings *instance;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        instance = [[UserSettings alloc] init];
    });
    return instance;
}

//////////////////////////////////////////////////////////////////////



/**
 *  服务端url，用来获取服务端的ip和端口
 */
- (NSString *)serverUrl
{
    NSString *url = [self.userDefaults objectForKey:KEY_SERVERURL];
    if (!url) {
        url = @"";
    }
    return url;
}

- (void)setServerUrl:(NSString *)serverUrl
{
    [_userDefaults setObject:serverUrl forKey:KEY_SERVERURL];
}

/**
 *  h5相关url
 */
- (NSString *)h5Url
{
    NSString *url = [self.userDefaults objectForKey:KEY_H5URL];
    if (!url) {
        url = @"";
    }
    return url;
}

- (void)setH5Url:(NSString *)h5Url
{
    [_userDefaults setObject:h5Url forKey:KEY_H5URL];
}


/**
 *  长链接(消息中心)url
 */
- (NSString *)msgCenterUrl
{
    NSString *url = [self.userDefaults objectForKey:KEY_MSGCENTERURL];
    if (!url) {
        url = @"";
    }
    return url;
}

- (void)setMsgCenterUrl:(NSString *)msgCenterUrl
{
    [_userDefaults setObject:msgCenterUrl forKey:KEY_MSGCENTERURL];
}


/**
 *  token
 */
- (NSString *)token
{
    NSString *strToken = [_userDefaults objectForKey:KEY_TOKEN];
//    NSLog(@"\n\n\n-----returnToken:%@-----", strToken);
    return strToken;
}

- (void)setToken:(NSString *)token
{
    // token允许赋值为@"",比如登出时
    if (nil != token) {
//        NSLog(@"\n\n\n-----saveToken:%@-----", token);
        [_userDefaults setObject:token forKey:KEY_TOKEN];
        [_userDefaults synchronize];
    }
}


/**
 *  areaCode
 */
- (NSString *)areaCode
{
    NSString *code = [self.userDefaults objectForKey:KEY_AREACODE];
    if (nil == code) code = @"";
    return code;
}

- (void)setAreaCode:(NSString *)strCode
{
    if (nil != strCode) {
        [_userDefaults setObject:strCode forKey:KEY_AREACODE];
    }
}

/**
 *  mobile
 */
- (NSString *)mobile
{
    NSString *phone = [self.userDefaults objectForKey:KEY_MOBILE];
    if (nil == phone) phone = @"";
    return phone;
}

- (void)setMobile:(NSString *)mobile
{
    if (nil != mobile) {
        mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
        [_userDefaults setObject:mobile forKey:KEY_MOBILE];
    }
}
/**
 *  用户id
 */
- (NSString *)userId
{
    NSString *userId = [self.userDefaults objectForKey:KEY_USERID];
    if (nil == userId) userId = @"";
    return userId;
}

- (void)setUserId:(NSString *)userId
{
    if (nil != userId) {
        [_userDefaults setObject:userId forKey:KEY_USERID];
    }
}

/**
 *  用户名字
 */
- (NSString *)name
{
    NSString *userName = [self.userDefaults objectForKey:KEY_NAME];
    if (nil == userName) userName = @"";
    return userName;
}

- (void)setName:(NSString *)name
{
    if (nil != name) {
        [_userDefaults setObject:name forKey:KEY_NAME];
    }
}

/**
 *  用户英文名字
 */
- (NSString *)eName
{
    NSString *eName = [self.userDefaults objectForKey:KEY_ENAME];
    if (nil == eName) eName = @"";
    return eName;
}

- (void)setEName:(NSString *)eName
{
    if (nil != eName) {
        [_userDefaults setObject:eName forKey:KEY_ENAME];
    }
}

/**
 *  用户性别
 */
- (NSInteger)sex {
    return [_userDefaults integerForKey:KEY_SEX];
}

- (void)setSex:(NSInteger)sex {
    [_userDefaults setInteger:sex forKey:KEY_SEX];
}

/**
 *  用户邮箱
 */
- (NSString *)mail
{
    NSString *mail = [self.userDefaults objectForKey:KEY_MAIL];
    if (nil == mail) mail = @"";
    return mail;
}

- (void)setMail:(NSString *)mail
{
    if (nil != mail) {
        [_userDefaults setObject:mail forKey:KEY_MAIL];
    }
}


/**
 *  用户头像
 */
- (NSString *)avatar
{
    NSString *strFullMobile = [NSString stringWithFormat:@"%@%@", UserSaveInfo.areaCode, UserSaveInfo.mobile];
    UserCacheInfoModel *cacheInfo = [UserSaveInfo userInfoForMobile:strFullMobile];
    if (nil == cacheInfo) {
        return @"";
    }
    return cacheInfo.userAavatar;
}

- (void)setAvatar:(NSString *)avatar
{
    if (nil != avatar) {
        NSString *strFullMobile = [NSString stringWithFormat:@"%@%@", UserSaveInfo.areaCode, UserSaveInfo.mobile];
        UserCacheInfoModel *cacheInfo = [UserSaveInfo userInfoForMobile:strFullMobile];
        if (nil == cacheInfo) {
            cacheInfo = [[UserCacheInfoModel alloc] init];
        }
        cacheInfo.userAavatar = avatar;
        [UserSaveInfo setUserInfo:cacheInfo forMobile:strFullMobile];
    }
}
/**
 *  所在公司名称
 */
- (NSString *)companyName
{
    NSString *companyName = [self.userDefaults objectForKey:KEY_COMPANY];
    if (nil == companyName) companyName = @"";
    return companyName;
}

- (void)setCompanyName:(NSString *)companyName
{
    if (nil != companyName) {
        [_userDefaults setObject:companyName forKey:KEY_COMPANY];
    }
}
/**
 *  所在公司职位
 */
- (NSString *)position
{
    NSString *position = [self.userDefaults objectForKey:KEY_POSITION];
    if (nil == position) position = @"";
    return position;
}

- (void)setPosition:(NSString *)position
{
    if (nil != position) {
        [_userDefaults setObject:position forKey:KEY_POSITION];
    }
}
/**
 *  认证id
 */
- (NSString *)authId
{
    NSString *authId = [self.userDefaults objectForKey:KEY_AUTHID];
    if (nil == authId) authId = @"";
    return authId;
}

- (void)setAuthId:(NSString *)authId
{
    if (nil != authId) {
        [_userDefaults setObject:authId forKey:KEY_AUTHID];
    }
}

/**
 *  微信
 */
- (NSString *)wechat
{
    NSString *chatAccount = [self.userDefaults objectForKey:KEY_WECHAT];
    if (nil == chatAccount) chatAccount = @"";
    return chatAccount;
}

- (void)setWechat:(NSString *)wechat
{
    if (nil != wechat) {
        [_userDefaults setObject:wechat forKey:KEY_WECHAT];
    }
}

/**
 *  facebook
 */
- (NSString *)facebook
{
    NSString *facebook = [self.userDefaults objectForKey:KEY_FACEBOOK];
    if (nil == facebook) facebook = @"";
    return facebook;
}

- (void)setFacebook:(NSString *)facebook
{
    if (nil != facebook) {
        [_userDefaults setObject:facebook forKey:KEY_FACEBOOK];
    }
}

/**
 *  名人名言
 */
- (NSString *)wisdom
{
    NSString *wisdom = [self.userDefaults objectForKey:KEY_WISDOM];
    if (nil == wisdom) wisdom = @"";
    return wisdom;
}

- (void)setWisdom:(NSString *)wisdom
{
    if (nil != wisdom) {
        [_userDefaults setObject:wisdom forKey:KEY_WISDOM];
    }
}

/**
 *  客户权限
 */
- (NSString *)vipLevel
{
    NSString *vipLevel = [self.userDefaults objectForKey:KEY_VIPLEVEL];
    if (nil == vipLevel) vipLevel = @"";
    return vipLevel;
}

- (void)setVipLevel:(NSString *)vipLevel
{
    if (nil != vipLevel) {
        [_userDefaults setObject:vipLevel forKey:KEY_VIPLEVEL];
    }
}


/**
 *  天气 —— 当前城市
 */
- (NSString *)currentCity
{
    NSString *currentCity = [self.userDefaults objectForKey:KEY_CURRENTCITY];
    if (nil == currentCity) currentCity = @"";
    return currentCity;
}

- (void)setCurrentCity:(NSString *)currentCity
{
    if (nil != currentCity) {
        [_userDefaults setObject:currentCity forKey:KEY_CURRENTCITY];
    }
}


/**
 *  天气 —— 当前地区
 */
- (NSString *)currentSubLocal
{
    NSString *currentSubLocal = [self.userDefaults objectForKey:KEY_CURRENTSUBLOCAL];
    if (nil == currentSubLocal) currentSubLocal = @"";
    return currentSubLocal;
}

- (void)setCurrentSubLocal:(NSString *)currentSubLocal
{
    if (nil != currentSubLocal) {
        [_userDefaults setObject:currentSubLocal forKey:KEY_CURRENTSUBLOCAL];
    }
}


/**
 *  天气 —— 温度
 */
- (NSString *)weatherTmp
{
    NSString *weatherTmp = [self.userDefaults objectForKey:KEY_WEATHERTMP];
    if (nil == weatherTmp) weatherTmp = @"";
    return weatherTmp;
}

- (void)setWeatherTmp:(NSString *)weatherTmp
{
    if (nil != weatherTmp) {
        [_userDefaults setObject:weatherTmp forKey:KEY_WEATHERTMP];
    }
}


/**
 *  天气 —— 天气状态代码
 */
- (NSString *)weatherCode
{
    NSString *weatherCode = [self.userDefaults objectForKey:KEY_WEATHERCODE];
    if (nil == weatherCode) weatherCode = @"";
    return weatherCode;
}

- (void)setWeatherCode:(NSString *)weatherCode
{
    if (nil != weatherCode) {
        [_userDefaults setObject:weatherCode forKey:KEY_WEATHERCODE];
    }
}


/**
 *  WXOpenID
 */
- (NSString *)WXOpenID
{
    NSString *WXOpenID = [self.userDefaults objectForKey:KEY_WX_OPENID];
    if (nil == WXOpenID) WXOpenID = @"";
    return WXOpenID;
}

- (void)setWXOpenID:(NSString *)WXOpenID
{
    if (nil != WXOpenID) {
        [_userDefaults setObject:WXOpenID forKey:KEY_WX_OPENID];
    }
}

/**
 *  WXAccessToken
 */
- (NSString *)WXAccessToken
{
    NSString *WXAccessToken = [self.userDefaults objectForKey:KEY_WX_AccessToken];
    if (nil == WXAccessToken) WXAccessToken = @"";
    return WXAccessToken;
}

- (void)setWXAccessToken:(NSString *)WXAccessToken
{
    if (nil != WXAccessToken) {
        [_userDefaults setObject:WXAccessToken forKey:KEY_WX_AccessToken];
    }
}


/**
 *  FBOpenID
 */
- (NSString *)FBOpenID
{
    NSString *FBOpenID = [self.userDefaults objectForKey:KEY_FB_OPENID];
    if (nil == FBOpenID) FBOpenID = @"";
    return FBOpenID;
}

- (void)setFBOpenID:(NSString *)FBOpenID
{
    if (nil != FBOpenID) {
        [_userDefaults setObject:FBOpenID forKey:KEY_FB_OPENID];
    }
}

/**
 *  FBAccessToken
 */
- (NSString *)FBAccessToken
{
    NSString *FBAccessToken = [self.userDefaults objectForKey:KEY_FB_AccessToken];
    if (nil == FBAccessToken) FBAccessToken = @"";
    return FBAccessToken;
}

- (void)setFBAccessToken:(NSString *)FBAccessToken
{
    if (nil != FBAccessToken) {
        [_userDefaults setObject:FBAccessToken forKey:KEY_FB_AccessToken];
    }
}


/**
 *  joinTeamName
 */
- (NSString *)joinTeamName
{
    NSString *joinTeamName = [self.userDefaults objectForKey:KEY_JOINTEAMNAME];
    if (nil == joinTeamName) joinTeamName = @"";
    return joinTeamName;
}

- (void)setJoinTeamName:(NSString *)joinTeamName
{
    if (nil != joinTeamName) {
        [_userDefaults setObject:joinTeamName forKey:KEY_JOINTEAMNAME];
    }
}

/**
 *  joinTeamToken
 */
- (NSString *)joinTeamToken
{
    NSString *joinTeamToken = [self.userDefaults objectForKey:KEY_JOINTEAMTOKEN];
    if (nil == joinTeamToken) joinTeamToken = @"";
    return joinTeamToken;
}

- (void)setJoinTeamToken:(NSString *)joinTeamToken
{
    if (nil != joinTeamToken) {
        [_userDefaults setObject:joinTeamToken forKey:KEY_JOINTEAMTOKEN];
    }
}


/**
 *  用户头像&用户名字
 */
- (UserCacheInfoModel *)userInfoForMobile:(NSString *)fullMobile {
    if ([StringUtil isEmpty:fullMobile]) {
        return nil;
    }

    // 获得plist文件路径
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [docPath stringByAppendingPathComponent:@"Avatar.plist"];
    // 获取保存的数据
    NSMutableDictionary *dicData = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    // 拼装key并获得数据对象
    NSString *key = [NSString stringWithFormat:@"%@%@", fullMobile, KEY_AVATARURL];
    NSData *data = [dicData objectForKey:key];
    UserCacheInfoModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return model;
}

- (void)setUserInfo:(UserCacheInfoModel *)userInfo forMobile:(NSString *)fullMobile {
    if ([StringUtil isNotEmpty:fullMobile] && nil != userInfo) {
        
        // 读取plist
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filename = [path stringByAppendingPathComponent:@"Avatar.plist"];
        if (![FileUtil isPathExist:filename]) {
            NSFileManager* fm = [NSFileManager defaultManager];
            [fm createFileAtPath:filename contents:nil attributes:nil];
        }
        
        NSString *key = [NSString stringWithFormat:@"%@%@", fullMobile, KEY_AVATARURL];
        NSMutableDictionary *realDic = [[NSMutableDictionary alloc] init];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filename];
        if (dic) {
            [realDic setDictionary:dic];
        }
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
        [realDic setObject:data forKey:key];
        
        [realDic writeToFile:filename atomically:YES];
    }
}

/**
 *  我创建的团队
 */
- (TeamFullInfo *)teamOfCreated
{
    NSData *data = [self.userDefaults objectForKey:KEY_CREATEDTEAM];
    TeamFullInfo *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return model;
}
- (void)setTeamOfCreated:(TeamFullInfo *)team
{
    if (nil != team) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:team];
        [self.userDefaults setObject:data forKey:KEY_CREATEDTEAM];
    }
}
- (void)clearCreatedTeam
{
    if (nil != [self.userDefaults objectForKey:KEY_CREATEDTEAM]) {
        [self.userDefaults removeObjectForKey:KEY_CREATEDTEAM];
    }
}

/**
 *  我加入的团队
 */
- (TeamFullInfo *)teamOfJoined
{
    NSData *data = [self.userDefaults objectForKey:KEY_JOINEDTEAM];
    TeamFullInfo *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return model;
}
- (void)setTeamOfJoined:(TeamFullInfo *)team
{
    if (nil != team) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:team];
        [self.userDefaults setObject:data forKey:KEY_JOINEDTEAM];
    }
}
- (void)clearJoinedTeam
{
    if (nil != [self.userDefaults objectForKey:KEY_JOINEDTEAM]) {
        [self.userDefaults removeObjectForKey:KEY_JOINEDTEAM];
    }
}


/**
 *  通知中心 - (登录用户对应)上一次系统通知的最大id
 */
- (NSString *)getSystemSaveMsgId:(NSString *)fullMobile
{
    if ([StringUtil isEmpty:fullMobile]) return nil;
    
    NSString *key = [NSString stringWithFormat:@"%@%@", fullMobile, KEY_MSGCENTER_SYSTEM_MSGID];
    NSString *strMsgId = [self.userDefaults objectForKey:key];
    return strMsgId;
}

- (void)setSystemSaveMsgId:(NSString *)strMsgId forMobile:(NSString *)fullMobile
{
    if ([StringUtil isEmpty:fullMobile]) return;
    
    NSString *key = [NSString stringWithFormat:@"%@%@", fullMobile, KEY_MSGCENTER_SYSTEM_MSGID];
    if (nil != strMsgId && 0 != strMsgId.length) {
        [_userDefaults setObject:strMsgId forKey:key];
    }
}


// 是否有新消息
- (BOOL)hasNewMessage
{
    BOOL value = [_userDefaults boolForKey:KEY_MSGCENTER_HAVE_NEWMSG];
    return value;
}

- (void)setHasNewMessage:(BOOL)hasNewMessage {
    [_userDefaults setBool:hasNewMessage forKey:KEY_MSGCENTER_HAVE_NEWMSG];
}

/**
 *  清楚缓存，发生在切换登录时
 */
- (void)clearCache
{
    UserSaveInfo.token = @"";
    UserSaveInfo.userId = @"";
    UserSaveInfo.name = @"";
    UserSaveInfo.eName = @"";
    UserSaveInfo.mail = @"";
    UserSaveInfo.companyName = @"";
    UserSaveInfo.position = @"";
    UserSaveInfo.authId = @"";
    UserSaveInfo.wechat = @"";
    UserSaveInfo.facebook = @"";
    
    UserSaveInfo.joinTeamName = @"";
    UserSaveInfo.joinTeamToken = @"";
    [UserSaveInfo clearCreatedTeam];
    [UserSaveInfo clearJoinedTeam];
}

@end
